package org.goldfish.distributed_framework.client;

import org.goldfish.distributed_framework.config.ClientConfig;

import java.util.ArrayList;
import java.util.List;

public class RpcClient {
    private static ClientConfig config;

    public static void setup(ClientConfig clientConfig) {
        config = clientConfig;
        System.out.println("[RpcClient] 初始化成功，准备发起远程调用");
    }

    public static Object call(String serviceName, String methodName, Object... params) {
        List<Class<?>> paramTypes = new ArrayList<>();
        for (Object param : params) {
            paramTypes.add(param.getClass());
        }
        return call(serviceName, methodName, paramTypes.toArray(new Class<?>[0]), params);
    }
    public static Object call(String serviceName, String methodName, Class<?>[] paramTypes, Object[] params) {
        try {
            String address = lookupService(serviceName);
            RpcRequest request = new RpcRequest(serviceName, methodName, paramTypes, params);
            RpcResponse response = RpcInvoker.invoke(address, request);
            return handleResponse(response);
        } catch (Exception e) {
            throw new RuntimeException("调用远程服务失败: " + serviceName + "." + methodName, e);
        }
    }

    private static String lookupService(String serviceName) throws Exception {
        String address = ServiceDiscovery.lookup(serviceName, config.registryAddress);
        if (address == null) {
            throw new IllegalStateException("找不到服务: " + serviceName);
        }
        return address;
    }

    private static Object handleResponse(RpcResponse response) {
        if (response.isSuccess()) {
            return response.getResult();
        } else {
            throw new RuntimeException("远程调用异常: " + response.getError());
        }
    }


}
